import React, { Component } from "react";
import Header from "../../components/Header/Header";
import { reqcartdelete, reqcartedit, reqcartlist} from "../../http/api";
import { $pre } from "../../http/http";
import "./Shop.less";
import yImg from "../../assets/img/y.jpeg";
import nImg from "../../assets/img/n.jpeg";
import { Button, SwipeAction, Dialog, Toast } from "antd-mobile";
import { filterPrice } from "../../filters";
export default class Shop extends Component {
  constructor() {
    super();
    this.state = {
      // 1.初始值
      arr: [],
      //全选
      allChecked: false,
    };

    this.isRequest = true;
  }
  componentDidMount() {
    //2.发请求
    this.getList();
  }
  // 请求列表
  async getList() {
    let res = await reqcartlist({
      uid: JSON.parse(sessionStorage.getItem("userInfo")).uid,
    });
    if (res.data.code === 200) {
      let arr = res.data.list ? res.data.list : [];
      let oldArr = this.state.arr;
      //补checked
      arr.forEach((item) => {
        let obj = oldArr.find((i) => i.id === item.id);
        item.checked = obj ? obj.checked : false;
      });

      this.setState(
        {
          arr: arr,
          allChecked:
            arr.length > 0 ? arr.every((item) => item.checked) : false,
        },
        () => {
          this.isRequest = true;
        }
      );
    }
  }
  //数量+
  async add(id) {
    let res = await reqcartedit({ id: id, type: 2 });
    if (res.data.code === 200) {
      Toast.show({
        content: res.data.msg,
      });
      //请求列表
      this.getList();
    }
  }
  // 数量-
  async sub(id, num) {
    if (num > 1) {
      // 由于用户可能多次连点，为了防止连点多次发请求，所以设置一个状态isRequest,真就发请求，假就不能发请求。
      // 一旦要发请求，立刻将isRequest=false，直到新的列表回来了，才将它改为isRequest=true,方便下一次请求。
      if (this.isRequest) {
        this.isRequest = false;
        let res = await reqcartedit({ id: id, type: 1 });
        if (res.data.code === 200) {
          Toast.show({
            content: res.data.msg,
          });
          //请求列表
          this.getList();
        }
      }
    } else {
      Toast.show({
        content: "宝贝不能再少了",
      });
    }
  }
  //删除
  async del(id) {
    let res = await reqcartdelete({ id: id });
    if (res.data.code === 200) {
      Toast.show({
        content: res.data.msg,
      });
      //请求列表
      this.getList();
    }
  }
  //点了全选
  changeAll() {
    this.setState(
      {
        allChecked: !this.state.allChecked,
      },
      () => {
        // 做
        this.state.arr.forEach((item) => {
          item.checked = this.state.allChecked;
        });
        //放
        this.setState({
          arr: this.state.arr,
        });
      }
    );
  }
  //修改了某一个
  changeOne(index) {
    let { arr } = this.state;
    // 做
    arr[index].checked = !arr[index].checked;

    //放
    this.setState({
      arr: arr,
      allChecked: arr.every((item) => item.checked),
    });
  }
  render() {
    let { arr, allChecked } = this.state;
    //总价
    let allPrice = arr.reduce(
      (v, i) => (i.checked ? v + i.price * i.num : v),
      0
    );
    return (
      <>
        <Header title="购物车"></Header>
        {arr.map((item, index) => (
          <SwipeAction
            key={item.id}
            closeOnAction={false}
            closeOnTouchOutside={false}
            rightActions={[
              {
                key: "delete",
                text: "删除",
                color: "danger",
                onClick: async () => {
                  await Dialog.confirm({
                    content: "确定要删除吗？",
                    onConfirm: () => {
                      this.del(item.id);
                    },
                  });
                },
              },
            ]}
          >
            <div className="item">
              <img
                className="checkbox"
                src={item.checked ? yImg : nImg}
                alt=""
              />
              <img
                onClick={() => this.changeOne(index)}
                className="img"
                src={$pre + item.img}
                alt=""
              />
              <div className="right">
                <h3>name:{item.goodsname}</h3>
                <div>price:{filterPrice(item.price)}</div>
                <div>
                  <Button onClick={() => this.sub(item.id, item.num)}>-</Button>
                  {item.num}
                  <Button onClick={() => this.add(item.id)}>+</Button>
                </div>
              </div>
            </div>
          </SwipeAction>
        ))}

        {/* 全选总价 */}
        <div className="footer">
          <div className="allChecked" onClick={() => this.changeAll()}>
            <img className="checkbox" src={allChecked ? yImg : nImg} alt="" />
            全选
          </div>
          <div className="allPrice">￥{filterPrice(allPrice)}</div>
        </div>
      </>
    );
  }
}
